<template>
  <div class="update-avatar">
    <img :src="img" ref="img" />
    <div class="toolbar">
      <span class="cancel" @click="$emit('close')">取消</span>
      <span class="confirm" @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user.js'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {}
  },

  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // 创建formData数据
        const formData = new FormData()
        formData.append('photo', blob)
        this.$toast.loading({
          message: '保存中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        })
        try {
          await updateUserAvatar(formData)
          this.$toast('更新成功')
        } catch (err) {
          this.$toast('更新失败')
        }
        this.$emit('close')
      })
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 裁剪框限制在画布当中
      dragMode: 'move', // 不允许直接选择裁剪框的大小，只能移动
      aspectRatio: 1, // 截图框的比例
      autoCropArea: 1, // 自动截取的比例，一边丁满
      cropBoxMovable: false, // 只能是背后的画布移动
      cropBoxResizable: false, // 截图区域不允许缩放大小
      background: false // 关闭自带背景
    })
  }
}
</script>

<style lang="less" scoped>
.img {
  display: block;
  max-width: 100%;
}
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
